<?php

namespace common\logics\cascader;

use Yii;
use common\helpers\Url;

/**
 * 公司层级列表
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class CompanyLogic extends \common\models\work\Company {

    /**
     * @var integer 深度
     */
    public static $deeps = 0;

    /**
     * @inheritdoc
     */
    public function fields() {
        $fields = [
            'id',
            'name',
            'parent_id',
        ];
        $deeps = 0;
        if (self::$deeps) {
            $deeps = 1;
            $parent = $this->parent;
            while ($parent) {
                $deeps++;
                if ($parent->parent_id) {
                    $parent = $parent->parent;
                } else {
                    $parent = null;
                }
            }
            if ($deeps <= self::$deeps) {
                $fields['children'] = 'activeChildren';
            }
        } else {
            $fields['children'] = 'activeChildren';
        }
        if (isset($fields['children']) && empty($this->activeChildren)) {
            unset($fields['children']);
        }
        $fields['deeps'] = function() use ($deeps) {
            return $deeps;
        };
        return $fields;
    }

    /**
     * @param integer $pid
     * @param boolean $deeps
     * @return \common\db\ActiveQuery
     */
    public static function findDeeps($pid = 0, $deeps = 0) {
        $query = static::find()->active();
        $query->andFilterWhere([
            'parent_id' => $pid
        ]);
        self::$deeps = $deeps;
        return $query;
    }

}
